#include "RecvMsg.h"
#include "kline_type.h"
#include <memory.h>
#include "SSHQLog.h"
#include "monitor_public_def.h"
#include <assert.h>
#include <string.h>

CRecvMsg::CRecvMsg()
	:buffer(0), bodyLen(0)
{
	buffer = new char[sizeof(ST_PackHead) + INIT_BODYLEN + 2];
	maxBodySize = INIT_BODYLEN;
}


CRecvMsg::~CRecvMsg()
{
	if (buffer)
		delete[] buffer;
	buffer = 0;
	maxBodySize = 0;
}

char * CRecvMsg::GetHead()
{
	return buffer;
}

int CRecvMsg::GetHeadLen()
{
	if (!buffer)
		return 0;

	return sizeof(ST_PackHead) + 1;
}

char * CRecvMsg::GetBody()
{
	if (!buffer)
		return NULL;

	return buffer + sizeof(ST_PackHead) + 1;
}

int CRecvMsg::GetBodyLen()
{
	if (!buffer)
		return 0;

	return bodyLen + 1;
}

bool CRecvMsg::decode_header()
{
	ST_PackHead head;
	memcpy(&head, GetHead() + 1, sizeof(head));


	if (buffer[0] != '{' || head.sLength < 0)
	{
		return false;
	}
	else if (head.sLength > maxBodySize)
	{
		if (buffer)
		{
			delete[] buffer;
			buffer = NULL;
			maxBodySize = 0;
		}

		buffer = new char[sizeof(ST_PackHead) + head.sLength + 2];
		
		if (buffer){
			memcpy(buffer, "{", 1);
			memcpy(buffer + 1, (char*)&head, sizeof(ST_PackHead));
			maxBodySize = head.sLength;
		}
		else
			return false;
	}
	
	bodyLen = head.sLength;
	return true;
}
